/**
 * Created by kevin on 17/4/5.
 */
var Router = require('koa-router')
var BasicAuth = require('../../util/BasicAuth')
var UserService = require('../../services/controllers/user.ctrl')
var SysService = require('../../services/controllers/sys.ctrl')
var ApiService = require('../../services/controllers/apiproxy.ctrl')

function register(app) {
    var router = new Router({
        prefix: '/manage'
    });

    router.get('/', function *(next) {
        this.body = 'welcome to manage site'
    });
    router.get('/login', function *(next) {
        this.body = 'welcome to login site'
    }).post('/login', function *(next) {
        var uid = this.request.body.uid;
        var pwd = this.request.body.pwd;
        if(!uid) {
            return this.body = RES.ERROR({}, '请输入用户账号', 500)
        }

        var user = yield *UserService.getUserByUid(uid);
        if(!user) {
            // Unprocessable Entity 422
            this.body = RES.ERROR({}, '用户不存在', 422)
        } else {
            let dt = user.toJSON();
            // 400 错误请求
            pwd == dt.password? this.body = RES.SUCCESS(dt, '用户登录成功', 200): this.body = RES.ERROR({}, '密码错误', 400)
        }
    });

    router.post('/user_if_exist', function *(next){
        console.log( 'uuid')
        var uid = this.request.body.uid;
        console.log(uid, 'uuid')
        if(!uid) {
            return this.body = RES.ERROR({}, '请输入用户账号', 500)
        }

        var user = yield *UserService.getUserByUid(uid);
        if(!user) {
            // Unprocessable Entity 422
            this.body = RES.SUCCESS({}, '用户不存在,可以注册', 200)
        } else {
            this.body = RES.ERROR({}, '用户已经存在,请更换用户名', 409)
        }
    })

    router.post('/register', function *(next){
        var user = this.request.body.user;
        console.log(user, 'this is user!!!')
        if(!user.uid) {
            return this.body = RES.ERROR({}, '请输入用户账号', 500)
        }
        var userOne;
        try {
            userOne = yield *UserService.createUser(user);
            this.body = RES.SUCCESS({}, '创建用户成功', 200)
        }catch (e) {
            this.body = RES.ERROR({}, '创建用户失败', 500)
        }
    })

    app.use(router.routes());
    app.use(router.allowedMethods());
}

module.exports = register;